import csv
import chardet
import os


def get_file_encoding(file):
    with open(file, 'rb') as f:
        text = f.read()
        return chardet.detect(text)


dir_name = "file"

file_list = os.listdir(dir_name)

for name in file_list:
    if name.endswith('csv'):
        file_path = '%s/%s' % (dir_name, name)
        charset_obj = get_file_encoding(file_path)
        print(charset_obj)
        # 处理中文
        if charset_obj.get('language') == 'Chinese':
            charset_obj['encoding'] = 'gbk'
        if not os.path.exists('%s/out' % dir_name):
            os.mkdir('%s/out' % dir_name)
        csv_file = open('%s/out/%s' % (dir_name,name), 'w', newline='', encoding='utf-8')
        spamwriter = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

        with open(file_path, newline='', encoding=charset_obj['encoding']) as csv_file:
            i = 0
            spamreader = csv.reader(csv_file, delimiter=',', quotechar='"')
            for row in spamreader:
                i += 1
                if i > 7:
                    # print(len(row))
                    spamwriter.writerow(row)
        csv_file.close()


